<?php
use think\Db;
// 上传文件
function upload($name, $file, $thumb = [])
{
    $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/' . $name . '/raw/');
    if ($info) {
        $image = \think\Image::open(ROOT_PATH . 'public' . DS . 'uploads/' . $name . '/raw/' . $info->getSaveName());
        $data = ['rawUrl' => '/uploads/' . $name . '/raw/' . $info->getSaveName()];
        if (!empty($thumb)) {
            if (isset($thumb[0])) {
                foreach ($thumb as $k => $v) {
                    $image->thumb($v['w'], $v['h'])->save(ROOT_PATH . 'public' . DS . 'uploads/' . $name . '/thumb_' . $v['w'] . '_' . $v['h'] . '/' . $info->getSaveName());
                    $data['thumbUrl'][$k] = '/uploads/' . $name . '/thumb_' . $v['w'] . '_' . $v['h'] . '/' . $info->getSaveName();
                }
            } else {
                $image->thumb($thumb['w'], $thumb['h'])->save(ROOT_PATH . 'public' . DS . 'uploads/' . $name . '/thumb_' . $thumb['w'] . '_' . $thumb['h'] . '/' . $info->getSaveName());
                $data['thumbUrl'] = '/uploads/' . $name . '/thumb_' . $thumb['w'] . '_' . $thumb['h'] . '/' . $info->getSaveName();
            }
        }
        if (!empty($data)) {
            foreach ($data as $key => &$val) {
                $data[$key . '_path'] = config('shopimage') . $val;
            }
        }
        return [
            'status' => 1,
            'msg' => '上传成功',
            'data' => $data
        ];
    } else {
        return [
            'status' => 0,
            'msg' => '上传失败'
        ];
    }
}


function getDbConfig()
{
    $res = \think\Db::name('driver_config')->where(['useUser' => 1, 'status' => 1])->select();
    $configArr = [];
    if (!empty($res)) {
        foreach ($res as $k => $v) {
            $configArr[$v['configKey']] = ['name' => $v['configName'], 'value' => $v['configVal']];
        }
    }
    return $configArr;
}

// 获取
function getBaiduCode()
{

}

// 根据经纬度 获取4个点
function getSquares($lat, $lng, $distance = 3)
{
    $dlng = 2 * asin(sin($distance / (2 * 6371)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);
    $dlat = $distance / 6371;
    $dlat = rad2deg($dlat);
    return array('left-top' => array('lat' => $lat + $dlat, 'lng' => $lng - $dlng),
        'right-top' => array('lat' => $lat + $dlat, 'lng' => $lng + $dlng),
        'left-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng - $dlng),
        'right-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng + $dlng)
    );
}

function testTree($data,$parentId = 0,$pid='parent_id',$id ='id'){
    $tree = [];
    foreach ($data as $key => $row) {
        if($row[$pid] == $parentId){
            $row['parent_id_path'] = $row['parent_id_path'];
            $tpm = testTree($data,$row[$id],$pid,$id);
            $row['c'] = $tpm;
            $tree[] = $row;
        }

    }
    return $tree;
}

/**
 * oraTreeDataPhp
 * 根据$data数据
 * 生成一个树形数组
 * 递归处理
 * 增加回调函数处理
 * @access public
 * @param array $data 待处理数据
 * @param function $callback 回调函数
 * @param int $parentId 待查询父级id
 * @param string $pid 父级id字段名称
 * @param string $id id字段名称
 * @return array $tree 返回数组
 * @author alexander<gt199899@gmail.com>
 * @version 2014-10-10 下午12:05:28
 * @version 2014-11-24 下午18:16:10
 * @copyright Show More
 */
function insertCartTreeData($data, $parentId = 0, $pid = 'admin_id', $id = 'id'){
    $tree = array();
    $rows = array();
    foreach($data as $row){
        if($row[$pid] == $parentId){
            $row['parent_id_path111'] = $parentId.'_'.$row[$id];
            $tmp = insertSellerTreeData($data, $row[$id], $pid, $id);
            if($tmp){
                $row['children'] = $tmp;
            }
            if(!empty($callback)){
               $children['children'] = isset($row['children']) && !empty($row['children']) ? $row['children'] : array();
               $tree[] = !empty($children['children']) ? array_merge(call_user_func($callback, $row), $children) : call_user_func($callback, $row);
               $rows[] = $row['id'];
               //$tree = Db::insert();
            }else{
                $rows[] = $row;
                $tree[] = $row;
            }
        }
    }
    unset($key, $value);
    return $rows;
}
/**
 * oraTreeDataPhp
 * 根据$data数据
 * 生成一个树形数组
 * 递归处理
 * 增加回调函数处理
 * @access public
 * @param array $data 待处理数据
 * @param function $callback 回调函数
 * @param int $parentId 待查询父级id
 * @param string $pid 父级id字段名称
 * @param string $id id字段名称
 * @return array $tree 返回数组
 * @author alexander<gt199899@gmail.com>
 * @version 2014-10-10 下午12:05:28
 * @version 2014-11-24 下午18:16:10
 * @copyright Show More
 */
function insertSellerTreeData($data, $parentId = 0, $pid = 'parent_id', $id = 'id'){
    $tree = array();
    $rows = array();
    foreach($data as $row){
        if($row[$pid] == $parentId){
            $row['parent_id_path111'] = $parentId.'_'.$row[$id];
            $tmp = insertSellerTreeData($data, $row[$id], $pid, $id);
            if($tmp){
                $row['children'] = $tmp;
            }
            if(!empty($callback)){
               $children['children'] = isset($row['children']) && !empty($row['children']) ? $row['children'] : array();
               $tree[] = !empty($children['children']) ? array_merge(call_user_func($callback, $row), $children) : call_user_func($callback, $row);
               $rows[] = $row['id'];
               //$tree = Db::insert();
            }else{
                $rows[] = $row;
                $tree[] = $row;
            }
        }
    }
    unset($key, $value);
    return $rows;
}
/**
 * oraTreeDataPhp
 * 根据$data数据
 * 生成一个树形数组
 * 递归处理
 * 增加回调函数处理
 * @access public
 * @param array $data 待处理数据
 * @param function $callback 回调函数
 * @param int $parentId 待查询父级id
 * @param string $pid 父级id字段名称
 * @param string $id id字段名称
 * @return array $tree 返回数组
 * @author alexander<gt199899@gmail.com>
 * @version 2014-10-10 下午12:05:28
 * @version 2014-11-24 下午18:16:10
 * @copyright Show More
 */
function getSellerTreeData($data, $parentId = 0, $pid = 'parent_id', $id = 'id',$callback =''){
    $tree = array();
    foreach($data as $row){
        if($row[$pid] == $parentId){
            $tmp = getSellerTreeData($data, $row[$id], $pid, $id);
            if($tmp){
                $row['children'] = $tmp;
            }
           if(!empty($callback)){
               $children['children'] = isset($row['children']) && !empty($row['children']) ? $row['children'] : array();
               $tree[] = !empty($children['children']) ? array_merge(call_user_func($callback, $row), $children) : call_user_func($callback, $row);
           }
            else{
                $tree[] = $row;
            }
        }
    }
    unset($key, $value);
    return $tree;
}

/**
     * 获取某个商品的评论统计
     * c0:全部评论数  c1:好评数 c2:中评数  c3差评数
     * rate1:好评率 rate2:中评率  c3差评率
     * @param $goods_id
     * @return array
     */
    function commentStatistics($goods_id)
    {
        $commentWhere = ['is_show'=>1,'goods_id'=>$goods_id,'parent_id'=>0,'user_id'=>['gt',0]];
        $c1 = Db::name('sh_comment')->where($commentWhere)->where('ceil((deliver_rank + goods_rank + service_rank) / 3) in (4,5)')->count();
        $c2 = Db::name('sh_comment')->where($commentWhere)->where('ceil((deliver_rank + goods_rank + service_rank) / 3) in (3)')->count();
        $c3 = Db::name('sh_comment')->where($commentWhere)->where('ceil((deliver_rank + goods_rank + service_rank) / 3) in (0,1,2)')->count();
        $c4 = Db::name('sh_comment')->where($commentWhere)->where("img !='' and img NOT LIKE 'N;%'")->count(); // 晒图
        $c0 = $c1 + $c2 + $c3; // 所有评论
        if($c0 <= 0){
            $rate1 = 100;
            $rate2 = 0;
            $rate3 = 0;
        }else{
            $rate1 = ceil($c1 / $c0 * 100); // 好评率
            $rate2 = ceil($c2 / $c0 * 100); // 中评率
            $rate3 = ceil($c3 / $c0 * 100); // 差评率
        }
        return array('c0' => $c0, 'c1' => $c1, 'c2' => $c2, 'c3' => $c3, 'c4'=>$c4,'rate1' => $rate1, 'rate2' => $rate2, 'rate3' => $rate3);
    }
    /**
     * 获取商品规格
     * @param $goods_id|商品id
     * @return array
     */

    function get_spec($goods_id)
    {
        //商品规格 价钱 库存表 找出 所有 规格项id
        $keys = Db::name('ShSpecGoodsPrice')->where("goods_id", $goods_id)->field("GROUP_CONCAT(`key` ORDER BY store_count desc SEPARATOR '_') as spec_key")->find();
        $filter_spec = array();
        if ($keys['spec_key']) {
         $specImage = Db::name('ShSpecImage')->where(['goods_id'=>$goods_id])->field("spec_image_id,src")->select();
            $specImage = array_column($specImage, 'src','spec_image_id');
            $keys = str_replace('_', ',', $keys['spec_key']);
            $keys = rtrim($keys,',');
            $sql = "SELECT a.name,a.order,b.* FROM slzd_sh_spec AS a INNER JOIN slzd_sh_spec_item AS b ON a.id = b.spec_id WHERE b.id IN($keys) ORDER BY b.id";
            $filter_spec2 = Db::query($sql);
            foreach ($filter_spec2 as $key => $val) {
                if($specImage){
                    $filter_spec[$val['name']][] = array(
                        'item_id' => $val['id'],
                        'item' => $val['item'],
                        'src' => $specImage[$val['id']],
                    );
                }else{
                    $filter_spec[$val['name']][] = array(
                        'item_id' => $val['id'],
                        'item' => $val['item'],
                    );
                }
            }
        }
        return $filter_spec;
    }
    function appPay($type){
        // 加载配置参数

    if($type == 1){
        $config = config();
        // 支付参数
        $payOrder = [
            'out_trade_no' => '1111111111111141234123', // 商户订单号
            'total_amount' => '1', // 支付金额
            'subject'      => 'test subject', // 支付订单描述
        ];

        // 实例支付对象
        $pay = new \Pay\Pay($config);

        try {
            $options = $pay->driver('alipay')->gateway('app')->apply($payOrder);
            var_dump($options);
        } catch (Exception $e) {
            echo "创建订单失败，" . $e->getMessage();
        }
    }else{
        // 支付参数
        $payOrder = [
            'out_trade_no'     => '45235', // 订单号
            'total_fee'        => '101', // 订单金额，**单位：分**
            'body'             => '测试', // 订单描述
            'spbill_create_ip' => '127.0.0.1', // 支付人的 IP
        ];

        // 实例支付对象
        $pay = new \Pay\Pay($config);

        try {
            echo '<pre>';
            $options = $pay->driver('wechat')->gateway('app')->apply($payOrder);
            var_export($options);
        } catch (Exception $e) {
            echo "创建订单失败，" . $e->getMessage();
        }
    }

}